package com.example.whereismystuff.views;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.whereismystuff.R;
import com.example.whereismystuff.R.id;
import com.example.whereismystuff.R.layout;
import com.example.whereismystuff.classes.*;
import com.facebook.*;
import com.facebook.Request.GraphUserCallback;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.model.*;
import com.facebook.widget.LoginButton;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.*;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;

/**
 * Login activity class
 * 
 * @author Johnnie will take care of all the interaction in the Input screen
 *         between the physical user and the UserManager.
 */
public class Login extends Activity {
	private static String APP_ID = "165121346976660"; // Replace your App ID
														// here

	// Instance of Facebook Class
	private Facebook facebook;
	private static final String[] PERMISSIONS = new String[] {"email","user_about_me", "user_birthday"};
	
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;
	EditText usernameInput, passwordInput;
	Button login, facebuk;
	Button signUp;
	AlertDialog.Builder alertBox;
	Intent i;

	String username, password;
	LoginDataBaseAdapter loginDataBaseAdapter;

	UserDataManager userManager;

	private int lockedCounter;

	private final int MAX_LOGIN_ATTEMPTS = 3;

	public static final String USERNAME_TAG = "Username";

	@Override
	/**
	 * Method used to Instantiate Object and set the Layout for the Activity
	 * @param Bundle
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		loginDataBaseAdapter = new LoginDataBaseAdapter(this);
		loginDataBaseAdapter = loginDataBaseAdapter.open();

		login = (Button) findViewById(R.id.login);
		facebuk = (Button) findViewById(R.id.authButton);
		signUp = (Button) findViewById(R.id.signUp);
		usernameInput = (EditText) findViewById(R.id.usernameInput);
		passwordInput = (EditText) findViewById(R.id.passwordInput);
		alertBox = new AlertDialog.Builder(this);
		//login = (Button) findViewById(R.id.login);

		lockedCounter = 0;
        facebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
		Toast.makeText(this, facebook.isSessionValid() + "", Toast.LENGTH_LONG).show();



	}

	@SuppressWarnings("deprecation")
	public void onFacebook(View v) {
	    mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("access_token", null);
	    long expires = mPrefs.getLong("access_expires", 0);
		//Toast.makeText(this, "Last try!!!!!!!!!!!!!!!", Toast.LENGTH_LONG).show();

	    if (access_token != null) {
	        facebook.setAccessToken(access_token);
			Toast.makeText(this, "acess token = null!", Toast.LENGTH_LONG).show();

	    }
	 
	    if (expires != 0) {
	        facebook.setAccessExpires(expires);
			Toast.makeText(this, "acesss = 0", Toast.LENGTH_LONG).show();
	    }
	 
		if (!facebook.isSessionValid()) {
			facebook.authorize(this, PERMISSIONS, new LoginDialogListener());

		}

		else {
	        Toast.makeText( this,"VALID", Toast.LENGTH_SHORT).show();

			addUser();
		}

	}
	
	class LoginDialogListener implements DialogListener {
		 
		public void onComplete(Bundle values) {
			addUser();
		}
	 
		public void onFacebookError(FacebookError e) {
			// TODO Auto-generated method stub
	 
		}
	 
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
	 
		}
	 
		public void onCancel() {
			// TODO Auto-generated method stub
	 
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		  facebook.authorizeCallback(requestCode, resultCode, data);
		  addUser();
		}
	
	public void addUser(){
        Request.executeMeRequestAsync(facebook.getSession(), new Request.GraphUserCallback() {

            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user, Response response) {
              if (user != null) {
            	  addToDb(user);
              }
            }
          });
        

	}
	
	public void addToDb(GraphUser user){

		String name = user.getFirstName().substring(0, 1).toLowerCase() + user.getLastName().toLowerCase()+ user.getBirthday().substring(8);

		if(!loginDataBaseAdapter.containsUser(name))
			loginDataBaseAdapter.insertEntry(name, "facebook", "false", "false");

		try {
			// Class c =
			// Class.forName("com.example.whereismystuff.views.ItemViewer");
			Class c = Class
					.forName("com.example.whereismystuff.views.DashboardView");
			Bundle extras = new Bundle();
			extras.putString("Username", name);
			i = new Intent(getApplicationContext(), c);
			i.putExtras(extras);
			startActivity(i);
			finish();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}


	
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.login, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.loginAsAdmin:
			moveToAdminLogin();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void moveToAdminLogin() {
		try {
			Class c = Class
					.forName("com.example.whereismystuff.views.AdminLogin");
			i = new Intent(getApplicationContext(), c);
			startActivity(i);
			finish();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * On Resume is called whenever the Activity is popped back into screen. It
	 * will clear each field and username and password.
	 */
	protected void onResume() {
		super.onResume();
		username = null;
		password = null;
		usernameInput.getText().clear();
		passwordInput.getText().clear();
	}




	public void transistion(String username) {
		try {
			// Class c =
			// Class.forName("com.example.whereismystuff.views.ItemViewer");
			Class c = Class
					.forName("com.example.whereismystuff.views.DashboardView");
			Bundle extras = new Bundle();
			// extras.putString("Username", usernameInput.getText().toString());
			i = new Intent(getApplicationContext(), c);
			i.putExtras(extras);
			startActivity(i);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Controls what happens when the Login button is clicked.
	 * 
	 * @param v
	 */
	public void onLogin(View v) {

		String storedPassword = loginDataBaseAdapter
				.getSingleEntry(usernameInput.getText().toString());
		if (loginDataBaseAdapter.getSingleEntryLock(
				usernameInput.getText().toString()).equals("false")
				&& passwordInput.getText().toString().equals(storedPassword)) {
			try {
				// Class c =
				// Class.forName("com.example.whereismystuff.views.ItemViewer");
				Class c = Class
						.forName("com.example.whereismystuff.views.DashboardView");
				Bundle extras = new Bundle();
				extras.putString("Username", usernameInput.getText().toString());

				i = new Intent(getApplicationContext(), c);
				i.putExtras(extras);
				startActivity(i);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			if (loginDataBaseAdapter.getSingleEntryLock(
					usernameInput.getText().toString()).equals("true")
					|| lockedCounter >= MAX_LOGIN_ATTEMPTS) {
				alertBox.setMessage("You have been locked out!");
				loginDataBaseAdapter.updateEntry(usernameInput.getText()
						.toString(), storedPassword, "true", "false");
				lockedCounter = 0;
			} else if (lockedCounter == MAX_LOGIN_ATTEMPTS - 1)
				Toast.makeText(this, "Last try!", Toast.LENGTH_SHORT);
			else if (loginDataBaseAdapter.getSingleEntry(
					usernameInput.getText().toString()).equals("NOT EXIST")) {
				alertBox.setMessage("Username does not exist!");
			} else
				alertBox.setMessage("Username and Password do not match!");
			alertBox.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alertBox.show();
			lockedCounter++;
		}

		if (loginDataBaseAdapter.getSingleEntryLock(
				usernameInput.getText().toString()).equals("true")) {
			alertBox.setMessage("You have been locked out!");
		} else if (!loginDataBaseAdapter.containsUser(usernameInput.getText()
				.toString())) {
			alertBox.setMessage("User does not exist!");

		} else if (passwordInput.getText().toString().equals(storedPassword)) {
			try {
				// Class c =
				// Class.forName("com.example.whereismystuff.views.ItemViewer");
				Class c = Class
						.forName("com.example.whereismystuff.views.DashboardView");
				Bundle extras = new Bundle();
				extras.putString("Username", usernameInput.getText().toString());
				i = new Intent(getApplicationContext(), c);
				i.putExtras(extras);
				startActivity(i);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			if (lockedCounter >= MAX_LOGIN_ATTEMPTS
					|| loginDataBaseAdapter.getSingleEntryLock(
							usernameInput.getText().toString()).equals("true")) {
				alertBox.setMessage("You have been locked out!");
				loginDataBaseAdapter.updateEntry(usernameInput.getText()
						.toString(), storedPassword, "true", "false");
				lockedCounter = 0;
			} else if (lockedCounter == MAX_LOGIN_ATTEMPTS - 1) {
				Toast.makeText(Login.this, "last try!", Toast.LENGTH_SHORT)
						.show();
				lockedCounter++;
			} else {
				alertBox.setMessage("Username and Password do not match!");
				lockedCounter++;
			}
			alertBox.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alertBox.show();
		}
	}

	/**
	 * Moves on to the SignUp activity.
	 * 
	 * @param v
	 */
	public void onSignUp(View v) {
		try {
			Class c = Class.forName("com.example.whereismystuff.views.SignUp");
			i = new Intent(getApplicationContext(), c);
			startActivity(i);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
